package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 判断是否套餐,如果是套餐,需要把审核状态设置为初始化
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT); // 把状态设置为0(初始化)
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED); // 把状态设置为无需审核
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);// 把销售状态设置为默认值
        serviceItem.setCreateTime(new Date());// 设置时间
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // this 调用当前对象 ,查询信息
        ServiceItem item = this.get(serviceItem.getId());
        // 已上架,不能编辑
        if (ServiceItem.SALESTATUS_ON.equals(item.getSaleStatus())) {
            throw new BusinessException("上架服务项目不能修改，请下架后再修改");
        }
        // 如果下架,审核中,不能编辑
        if (ServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())) {
            throw new BusinessException("服务项目审核中，不可修改");
        }
        // 如果下架,审核通过,编辑的后提交,审核状态修改为初始化状态
        if (ServiceItem.AUDITSTATUS_APPROVED.equals(item.getAuditStatus())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            // 原来什么状态,设置什么状态
            serviceItem.setAuditStatus(item.getAuditStatus());
        }
        // 套餐没有被修改,获取原来的
        serviceItem.setCarPackage(item.getCarPackage());
        // 防止前台恶意对销售状态进行设置，代码中主动设置销售状态为下架状态
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateByPrimaryKey(serviceItem);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        /**
         *       1.如果已上架就不需要再进行上架
         *       2.如果是套餐,如果不是审核通过的状态，是不能上架的，抛出异常.
         *       3.在数据库中进行状态修改
         */
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) &&
                !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) {
            throw new BusinessException("套餐服务项需要审核通过之后才能上架");
        }
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public TablePageInfo<ServiceItem> selectAllSaleOnList(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectAllSaleOnList(qo));
    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        //合理性校验
        ServiceItem serviceItem = this.get(id);
        if (ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus()) //处于上架状态
                || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage()) //非套餐
                || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus()) //审核中
                || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus()) //审核通过
                || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus()) //无需审核
        ){
            throw new BusinessException("参数异常");
        }
        //修改服务状态,为审核中
        serviceItemMapper.changeAuditStatus(id,ServiceItem.AUDITSTATUS_AUDITING);
        //审核信息
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemInfo(serviceItem.getInfo()); //套餐备注
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());//套餐折扣价格
        audit.setBpmnInfoId(bpmnInfoId);//
        audit.setCreateTime(new Date());//创建时间
        audit.setCreator(ShiroUtils.getUser().getUserName());//创建人
        audit.setInfo(info);//备注
        audit.setAuditorId(director);//审核人
        audit.setServiceItemId(id);//服务项id
        audit.setServiceItemName(serviceItem.getName());//服务项名称
        //保存审核数据
        carPackageAuditMapper.insert(audit);
        //启动流程定义实例
        HashMap<String, Object> map = new HashMap<>();
        if (director != null) {
            map.put("director",director);
        }
        if (finance != null) {
            map.put("finance",finance);
        }
        //折扣价
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        //获取对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        //启动流程
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(),
                        audit.getId().toString(), map);
        //审核对象关联实例id
        audit.setInstanceId(processInstance.getId());
        carPackageAuditMapper.updateByPrimaryKey(audit);

    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}
